#!/usr/bin/perl

#arguments
# arg1. input pcap file name
# arg2. output pcap file name
# arg3. file with original timestamps in time order (must be >= length of packets)
# arg4. file with new timestamps in time order (must be >= length of packets)
# arg5. length of packets to adjust timestamp (starting from 1st packet)

#note
# new timestamp always starts from 1.000, because editcap cannot accurately substract the timestamp to a number <=1

$numArgs = $#ARGV + 1;
if($numArgs != 5)
{
	print("num of arguments != 5\n");
	return;
}

if($ARGV[4]<=0)
{
	print("length of packet to adjust timestamp must be greater than 0\n");
	return;
}

open(OUTPUT1, ">$ARGV[1]") or die "$ARGV[1] cannot be created.\n";
open(INPUT1, $ARGV[2]) or die "$ARGV[3] cannot be opened.\n";
open(INPUT2, $ARGV[3]) or die "$ARGV[4] cannot be opened.\n";

$start_time=1;

for($i=1; $i<=$ARGV[4]; $i++)
{
	
	$old_time = <INPUT1>;
	$new_time = <INPUT2>;
	chomp($old_time);
	chomp($new_time);
	$adjusted_time=$new_time-$old_time+$start_time;
	$formatted_at=sprintf("%.6f", $adjusted_time);
	#print("$old_time, $new_time, $adjusted_time $formatted_at\n");

	system("editcap -v -r -t $formatted_at $ARGV[0] $ARGV[1]_$i $i");
}

#merge
$command = "mergecap -w $ARGV[1] ";
for($i=1; $i<=$ARGV[4]; $i++)
{
	$command = $command.$ARGV[1]."_".$i." ";
}
#print "$command\n";
system("$command");

#delete
for($i=1; $i<=$ARGV[4]; $i++)
{
	system("rm $ARGV[1]_$i");
}




